package com.dglg.spring.controller;

import com.dglg.spring.model.Document;
import com.dglg.spring.model.Teacher;
import com.dglg.spring.service.DocumentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;

@RestController
public class FileUploadController {

    // 读取配置文件中的路径 static/files
    @Value("${fileLocation}")
    private String fileLocation;
    @Autowired
    DocumentService documentService;

    @PostMapping("/upload")
    public Result upload(MultipartFile file, HttpServletRequest request) throws IOException {
        // 获得 classpath 的绝对路径
        String realPath = ResourceUtils.getURL("classpath:").getPath() + fileLocation;

        Document document = new Document();
        document.setClassName(request.getParameter("className"));
        document.setLoadPerson(request.getParameter("loadPerson"));
        document.setDocumentName(file.getOriginalFilename());


        File newFile = new File(realPath);
        // 如果文件夹不存在、则新建
        if (!newFile.exists()) newFile.mkdirs();
        // 上传
        Date date = new Date();
        String fileName = date.getTime() +"@" + file.getOriginalFilename();
        document.setAfterLoadName(fileName);   // 获取上传后的文件名
        file.transferTo(new File(newFile, fileName));
        int count = documentService.insertFileMess(document);
        Integer code = fileName != null ? Code.GET_OK : Code.GET_ERR;
        String msg = fileName != null ? "文件上传成功！" : "文件上传失败，请重试！";

        return new Result(code, fileName, msg);
    }

    @RequestMapping(value = "/deleteFile", method = RequestMethod.POST)
    public Result deleteFile(HttpServletRequest request) {

        int count = documentService.deleteFile(request.getParameter("className"), request.getParameter("documentName"));

        Integer code = count != 0 ? Code.GET_OK : Code.GET_ERR;
        String msg = count != 0 ? "数据删除成功！" : "数据删除失败，请重试！";

        return new Result(code, count, msg);
    }

    @GetMapping("download")
    public Result download(String fileName, HttpServletResponse response) throws IOException {
        // 获得待下载文件所在文件夹的绝对路径
        String realPath = ResourceUtils.getURL("classpath:").getPath() + fileLocation;
        // 获得文件输入流
        FileInputStream inputStream = new FileInputStream(new File(realPath, fileName));
        // 设置响应头、以附件形式打开文件
        response.setHeader("content-disposition", "attachment; fileName=" + fileName);
        ServletOutputStream outputStream = response.getOutputStream();
        int len = 0;
        byte[] data = new byte[1024];
        while ((len = inputStream.read(data)) != -1) {
            outputStream.write(data, 0, len);
        }

        Integer code = len != -1? Code.GET_OK : Code.GET_ERR;
        String msg = len != -1 ? "文件下载成功！" : "文件下载失败，请重试！";

        outputStream.close();
        inputStream.close();

        return new Result(code, len, msg);
    }

    // 根据实训班查找文档信息
    @GetMapping("/getDocuments/{className}")
    public Result getDocuments(@PathVariable("className") String className){
        List<Document> documents = this.documentService.getDocuments(className);
        Integer code = documents != null ? Code.GET_OK : Code.GET_ERR;
        String msg = documents != null ? "数据查询成功！" : "数据查询失败，请重试！";

        return new Result(code, documents, msg);
    }

}
